<?php
require_once 'common.php';
/**
 * 应用模型
 * @author xucongbin
 *
 */
class OaServiceOPLogModel extends OpModel
{
    // 操作状态
    const OPERATION_UNDO = 1; // 未操作
    const OPERATION_TRY = 2; // 重试
    const OPERATION_FAILURE = 3; // 失败
    const OPERATION_SUCCESS = 4; // 成功
    const OPERATION_SENT = 5; // 成功
   
    protected static $_serviceOPStatus = array(
        self::OPERATION_UNDO => '未操作', 
        self::OPERATION_SENT => '发送请求',
        self::OPERATION_TRY => '重试',
        self::OPERATION_FAILURE => '失败',
        self::OPERATION_SUCCESS => '成功'        
    );
    //操作类型 
    const OP_TYPE_SERVICE_AUTHEN = 1;
    const OP_TYPE_SERVICE_BILLING = 2;
    const OP_TYPE_SERVICE_PAYMENT = 3;
    const OP_TYPE_SERVICE_QUANQUAN = 4;
    const OP_TYPE_SERVICE_PROTECT = 5;
    const OP_TYPE_SERVICE_HELP = 6;
    const OP_TYPE_SERVICE_INTEGRAL = 7;
    const OP_TYPE_SERVICE_DIVIDEND = 8;
    const OP_TYPE_AREA_PAYMENT = 9;
    const OP_TYPE_AREA_BILLING = 10;
    const OP_TYPE_GROUP_PAYMENT = 11;
    const OP_TYPE_TRUST_IP_AUTHEN = 12;
    const OP_TYPE_TEST_ACCOUNT_AUTHEN = 13;
    const OP_TYPE_TEST_ACCOUNT_PAYMENT = 14;
    protected static $_serviceOPType = array(
        self::OP_TYPE_SERVICE_AUTHEN => '认证服务', 
        self::OP_TYPE_SERVICE_BILLING => '计费服务',
        self::OP_TYPE_SERVICE_PAYMENT => '支付服务',
        self::OP_TYPE_SERVICE_QUANQUAN => '圈圈服务',
        self::OP_TYPE_SERVICE_PROTECT => '防沉迷服务', 
        self::OP_TYPE_SERVICE_HELP => '彩虹帮助服务',
        self::OP_TYPE_SERVICE_INTEGRAL => '积分服务',
        self::OP_TYPE_SERVICE_DIVIDEND => '分红服务',
        self::OP_TYPE_AREA_PAYMENT => '同步支付区', 
        self::OP_TYPE_AREA_BILLING => '同步计费区',
        self::OP_TYPE_GROUP_PAYMENT => '同步计费组',
        self::OP_TYPE_TRUST_IP_AUTHEN => '信任IP同步',
        self::OP_TYPE_TEST_ACCOUNT_AUTHEN => '测试帐号同步认证',
        self::OP_TYPE_TEST_ACCOUNT_PAYMENT => '测试帐号同步支付'
    );
    //调用方法
    const METHOD_TYPE_ADD = 1;
    const METHOD_TYPE_UPDATE = 2;
    const METHOD_TYPE_CLOSE = 3;
    const METHOD_TYPE_SYNC = 4;
    const METHOD_TYPE_GET = 5;
    public static $_methodTranslate = array(
        self::METHOD_TYPE_ADD => 'add', 
        self::METHOD_TYPE_UPDATE => 'update',
        self::METHOD_TYPE_CLOSE => 'close',
        self::METHOD_TYPE_SYNC => 'sync',
        self::METHOD_TYPE_GET => 'get'
    );
    const SERVICE_OPLOG_TABLE = "service_operation_log";
    private $_serviceOPLogDb;
    public static function getConstantValueByName ($name, $default = 0)
    {
        return self::_getConstByName($name, '', $default, 'OaServiceOPLogModel');
    }
    public function __construct ($logger = null)
    {
        if (is_null($logger)) {
            $logger = getOaModelLogger();
        }
        parent::__construct($logger);
        $dbConfig = Oa_Util_Config::getSingleDbConfig(OA_WEB_DB_CLUSTER_ID);
        $db = OpDbModel::getInstance($dbConfig, $logger);
        $this->_serviceOPLogDb = new OpTableModel($db, self::SERVICE_OPLOG_TABLE, $logger);
    }
    /**
     * 获取操作状态 
     * @param int $status 
     * 
     * @return array|string $status不为null，返回状态名称；其它返回全部动作
     */
    public function getServiceOPStatus ($status = null)
    {
        if ($status) {
            return self::$_serviceOPStatus[$status];
        }
        return self::$_serviceOPStatus;
    }
	/**
     * 获取操作类型
     * @param int $type
     * 
     * @return array|string $type不为null，返回状态名称；其它返回全部类型
     */
    public function getServiceOPType ($type = null)
    {
        if ($type) {
            return self::$_serviceOPType[$type];
        }
        return self::$_serviceOPType;
    }
    /**
     * 获取记录列表
     * @param array $where array(environment=> 环境
     * app_id=> 产品ID
     * op_type=> 操作类型
     * method_type=>调用方法)
     * @param int $offset
     * @param int $count 
     * @param string $sort
     * @param array $otherWhere 附加条件
     * 
     * @return mixed
     */
    public function getServiceOPLogList ($where, $offset = 0, $count = null, $sort = null, $otherWhere=array())
    {        
        $sql = "SELECT * FROM " . self::SERVICE_OPLOG_TABLE . getSqlCond($where, $offset, $count, $sort, 
            $otherWhere);
        $result = $this->_serviceOPLogDb->query($sql);
        return $result;
    }
    /**
     * 获取记录条数
     * @param array $where array(environment=> 环境
     * app_id=> 产品ID
     * op_type=> 操作类型
     * method_type=>调用方法)
     * @param array 附加条件 $otherWhere
     * 
     * @return array|boolean
     */
    public function getServiceOPLogCount ($where, $otherWhere=array())
    {
        $sql = "SELECT COUNT(*) FROM " . self::SERVICE_OPLOG_TABLE . getSqlCond($where, 0, 0, null, 
            $otherWhere);
        $result = $this->_serviceOPLogDb->query($sql, PDO::FETCH_NUM);
        return (int) $result[0][0];
    }
    /**
     * 添加服务操作日志
     * @param string $taskId 
     * @param array $row array(`op_type`=>操作类型, `status`=>操作状态, data=>数据，
     * `create_time`=>添加时间, environment=> 环境, method_type=>调用方法)
     * @param string $operationId 主键
     * @return string|boolean(成功返回主键，失败返回false)
     */
    public function createServiceOPLog ($taskId, $row = array(), $operationId=null)
    {
        $row = array_merge(array(
            'task_id' => $taskId, 
            'operation_id' => $operationId, 
        ), $row);
        
        if (! isset($row['create_time'])) {
            $row['create_time'] = date('Y-m-d H:i:s');
        }
        if (!$row['operation_id']) {
        	$row['operation_id'] = $this->getUniqueLogId($taskId);
        }
        if (!$this->_serviceOPLogDb->insert($row, null, false)) {
        	return false;
        }
        return $row['operation_id'];
    }
    /**
     * 修改服务操作日志状态
     * @param int $status 操作状态
     * @param string $operationId 主键
     * 
     * @return boolean 
     */
    public function setServiceOPStatus($status, $operationId)
    {
        $row = array('status'=>$status);
        return $this->_serviceOPLogDb->update(array(
            'id' => $operationId
        ), $row);
    }
	/**
     * 修改服务操作日志状态
     * @param array $row array(`op_type`=>操作类型, `status`=>操作状态, data=>数据, environment=> 环境, method_type=>调用方法)
     * @param string $operationId 主键
     * 
     * @return boolean 
     */
    public function modifyServiceOPLog($row, $operationId)
    {
        if (!$this->getServiceOPLogCount(array('operation_id' => $operationId))) {
        	$this->_logger->log("ServiceOPLog Not Exists: {$operationId}");
        	return false;
        }
        return $this->_serviceOPLogDb->update(array(
            'operation_id' => $operationId
        ), $row);
    }
    /**
     * 删除
     * @param array $where array(operation_id=> 日志ID
     * task_id=> 
     * op_type=> 操作类型
     * status=>操作状态
     * @return boolean
     */
    public function deleteServiceOPLog($where)
    {
        if(!$where){
            return false;
        }
        return $this->_serviceOPLogDb->delete($where);
    }
	/**
     * 获取单条记录
     * @param int $operationId 主键
     * @param array $columns array(environment=> 环境
     * taskId => task外键
     * app_id=> 产品ID
     * environment=> 环境, 
     * method_type=>调用方法
     * op_type=>操作类型,
     * status=>操作状态,
     * data=>操作数据源)
     * 
     * @return mixed
     */
    public function getServiceOPLog ($operationId, $columns = null)
    {        
        $result =  $this->_serviceOPLogDb->getRow(array('operation_id' => $operationId), null, $columns);
        if ($result === false) {
//            $this->_logger->log("query failed");
            return false;
        }
        if (isset($result['op_type'])) {
        	$result['op_type_name'] = self::$_serviceOPType[$result['op_type']];
        }
    	if (isset($result['status'])) {
        	$result['status_name'] = self::$_serviceOPStatus[$result['status']];
        }
        
        return $result;
    }
    public function getUniqueLogId($taskId=0)
    {
        $str = $_SERVER['HTTP_USER_AGENT'] . $_SERVER['REMOTE_ADDR'] . $taskId . microtime(true) . rand();
        return md5($str);  
    }
}